package net.j4love.grpc.demo.service;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

/**
 * @author He Peng
 * @create 2018-05-13 15:35
 * @update 2018-05-13 15:35
 * @updatedesc : 更新说明
 * @see
 */
public class GrpcServerBootstrap {

    private Server server;

    public static void main(String[] args) throws Exception {
        GrpcServerBootstrap grpcServer = new GrpcServerBootstrap();
        grpcServer.start(6666);
        grpcServer.blockUntilShutdown();
    }

    private void start(int port) throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(new GreeterServiceImpl())
                .build().start();
        System.out.println("gRPC server start in " + port + " port");
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                GrpcServerBootstrap.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
